package com.learn.config;

import com.learn.io.Resources;
import com.learn.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * 通过读取sqlMapConfig.xml获取数据库配置信息和所有Mapper.xml配置的地址,并且封装到Configuration对象中
 */
public class XmlConfigBuilder {
    private XmlConfigBuilder() {

    }

    public static Configuration parseConfig(InputStream in) throws DocumentException, PropertyVetoException {
        Configuration configuration = new Configuration();
        //将sqlMapConfig.xml转换成了Document对象
        Document document = new SAXReader().read(in);
        Element rootElement = document.getRootElement();
        List<Element> propertyElements = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        for (Element propertyElement :
                propertyElements) {
            String name = propertyElement.attributeValue("name");
            String value = propertyElement.attributeValue("value");
            properties.setProperty(name, value);
        }
        System.out.println(properties);
        //创建连接池
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("user"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(comboPooledDataSource);
        //mapper部分
        List<Element> mapperElements = rootElement.selectNodes("//mapper");
        /**
         * 创建一个专门解析Mapper.xml的类
         * XmlMapperBuilder
         * void parse(InputStream input)
         */
        XmlMapperBuilder xmlMapperBuilder = new XmlMapperBuilder(configuration);
        for (Element mapperElement :
                mapperElements) {
            String mapperPath = mapperElement.attributeValue("resource");
            InputStream inputStream = Resources.getResourceAsStream(mapperPath);
            xmlMapperBuilder.parse(inputStream);
        }
        return configuration;
    }
}
